import datetime
import os
import random
import subprocess
import time
from PySide6.QtWidgets import QApplication, QMainWindow, QTableWidgetItem
from main_ui import Ui_MainWindow
from PySide6 import QtCore
from PySide6.QtGui import QIcon, QPixmap
import webbrowser
from PIL import Image, ImageQt
import shelve
from mutagen import File, mp3
import pygame
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = cast(interface, POINTER(IAudioEndpointVolume))

# 初始化音频模块（必须最先执行）
pygame.mixer.init()

import dkPhoto

point = 0
tabList = None
musicList = None
bePlayed = None
musicPoint = 0
musicloop = False
sxPoint = 0
voiceStep = -1
voiceSize = 2
isStop = True
current_time = 0
isImmerse = False
tomato = []
jjs = ""
dateStr = ""
sche = None
lastMusicPoint = -1
dktg = ["00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000"]
def saveData(name, data):
    with shelve.open('C:\\ProgramData\\LearningTools\\data\\data.db') as shelf:
        shelf[name] = data
def readData(name):
    with shelve.open('C:\\ProgramData\\LearningTools\\data\\data.db') as shelf:
        return shelf[name]
def findData(name):
    with shelve.open('C:\\ProgramData\\LearningTools\\data\\data.db') as shelf:
        if name in shelf:
            return True
        else:
            return False
        
# 以上函数都是用来数据库管理的
# 接下来的函数就是用来获取固定格式时间的,用来给计算打卡提供服务

def timeStrGet():
    return datetime.datetime.now().strftime("%Y%m%d")
# print(timeStrGet()) # test
class MainWindow(QMainWindow):
    
    def __init__(self):
        global tabList, musicList, bePlayed, jjs, dateStr, sche, dktg
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()  # UI类的实例化()
        self.ui.setupUi(self)

        self.timer = QtCore.QTimer(self)  # 创建 QTimer 对象
        self.timer.timeout.connect(self.timeUpdate)  # 将 timeout 信号连接到槽函数
        self.timer.start(0)  # 单位毫秒
        
        # 记录一下tab
        tabList = [
            [self.ui.tab,True],
            [self.ui.tab_2,False],
            [self.ui.tab_3,False],
            [self.ui.tab_4,False],
            [self.ui.tab_6,False],
            # [self.ui.tab_9,False],
            [self.ui.tab_8,False],
            # [self.ui.tab_7,False],
            [self.ui.tab_10,False],
            [self.ui.tab_5,True]
            ]
        # 先把跳转做出来
        self.ui.pushButton.clicked.connect(self.home)
        self.ui.pushButton_2.clicked.connect(self.study)
        self.ui.pushButton_3.clicked.connect(self.tomato)
        self.ui.pushButton_5.clicked.connect(self.note)
        self.ui.pushButton_4.clicked.connect(self.date)
        # self.ui.pushButton_8.clicked.connect(self.plan)
        self.ui.pushButton_7.clicked.connect(self.census)
        # self.ui.pushButton_6.clicked.connect(self.manage)
        self.ui.pushButton_10.clicked.connect(self.about)
        # self.ui.tabWidget.setMovable(True)

        # 接下来是总体的初始化部分，我们需要将除了欢迎的所有标签页全部隐藏起来
        for i in range(6):
            self.ui.tabWidget.removeTab(1)

        self.ui.pushButton_13.clicked.connect(self.date)
        self.ui.pushButton_11.clicked.connect(self.useExplain)
        self.ui.pushButton_12.clicked.connect(self.programDoc)
        self.ui.pushButton_29.clicked.connect(self.programDoc)

        self.ui.commandLinkButton_2.clicked.connect(self.userMusic)
        self.ui.commandLinkButton.clicked.connect(self.userData)

        pixmap = QPixmap.fromImage(ImageQt.toqimage(dkPhoto.makeDkb(["2026年跨年", datetime.date(2026, 1, 1)], ["2027届高考", datetime.date(2027, 6, 1)])))
        self.ui.pushButton_14.setIcon(QIcon(pixmap))
        self.ui.pushButton_14.clicked.connect(self.dk)
        if findData("DK_DATE"):
            if readData("DK_DATE") == datetime.datetime.now().strftime("%Y-%m-%d"):
                img = readData("_DK")
                pixmap = QPixmap.fromImage(ImageQt.toqimage(img))
                self.ui.pushButton_14.setIcon(QIcon(pixmap))

        # 我们还需要去获取音乐的列表，方便播放
        musicList = os.listdir("C:\\ProgramData\\LearningTools\\music")
        bePlayed = musicList[musicPoint]

        # 设置一下自习室的按钮
        self.ui.pushButton_21.setIcon(QIcon(QPixmap.fromImage(ImageQt.toqimage(Image.open('C:\\ProgramData\\LearningTools\\material\\img\\last.png')))))
        self.ui.pushButton_20.setIcon(QIcon(QPixmap.fromImage(ImageQt.toqimage(Image.open('C:\\ProgramData\\LearningTools\\material\\img\\sx1.png')))))
        self.ui.pushButton_19.setIcon(QIcon(QPixmap.fromImage(ImageQt.toqimage(Image.open('C:\\ProgramData\\LearningTools\\material\\img\\next.png')))))
        self.ui.pushButton_17.setIcon(QIcon(QPixmap.fromImage(ImageQt.toqimage(Image.open('C:\\ProgramData\\LearningTools\\material\\img\\stop.png')))))
        self.ui.pushButton_18.setIcon(QIcon(QPixmap.fromImage(ImageQt.toqimage(Image.open('C:\\ProgramData\\LearningTools\\material\\img\\v2.png')))))

        self.ui.pushButton_21.clicked.connect(self.last)
        self.ui.pushButton_20.clicked.connect(self.sx)
        self.ui.pushButton_19.clicked.connect(self.next)
        self.ui.pushButton_17.clicked.connect(self.stop)
        self.ui.pushButton_18.clicked.connect(self.voice)

        self.ui.pushButton_16.clicked.connect(self.immerse)
        # 关于番茄钟
        self.ui.pushButton_22.clicked.connect(self.startTomato)
        self.ui.pushButton_23.clicked.connect(self.stopTomato)
        if findData("jjs"):
            jjs = readData("jjs")
        else:
            saveData("jjs", "")
        self.ui.textEdit.setText(jjs)

        self.ui.calendarWidget.clicked.connect(self.on_date_clicked)

        for i in range(25):
            self.ui.tableWidget_2.setItem(i,0,QTableWidgetItem())
            self.ui.tableWidget_2.setItem(i,1,QTableWidgetItem())
            self.ui.tableWidget.setItem(i,0,QTableWidgetItem())
            self.ui.tableWidget.setItem(i,1,QTableWidgetItem())
        
        if findData("sche"):
            sche = readData("sche")
        else:
            saveData("sche", {})
            sche = readData("sche")

        if findData("dktg"):
            dktg = readData("dktg")
        else:
            saveData("dktg", ["00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000","00000000"])
            dktg = readData("dktg")

        self.on_date_clicked(date=QtCore.QDate(datetime.datetime.today().year, datetime.datetime.today().month, datetime.datetime.today().second))
    def userMusic(self):
        subprocess.Popen(['explorer', "C:\\ProgramData\\LearningTools\\music"])
    def userData(self):
        subprocess.Popen(['explorer', "C:\\ProgramData\\LearningTools"])
    def on_date_clicked(self, date):
        global dateStr, sche
        
        dateStr = date.toString('yyyy-MM-dd')
        if dateStr in sche:
            for i in range(25):
                self.ui.tableWidget_2.item(i,0).setText(sche[date.toString('yyyy-MM-dd')][i][0])
                self.ui.tableWidget_2.item(i,1).setText(sche[date.toString('yyyy-MM-dd')][i][1])
        else:
            sche[dateStr] = [["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""]]
            for i in range(25):
                self.ui.tableWidget_2.item(i,0).setText(sche[date.toString('yyyy-MM-dd')][i][0])
                self.ui.tableWidget_2.item(i,1).setText(sche[date.toString('yyyy-MM-dd')][i][1])

    def startTomato(self):
        global tomato
        tomato = [int(time.time())]
        for i in range(12):
            tomato.append(tomato[len(tomato)-1] + (self.ui.timeEdit.dateTime().time().minute()*60) + self.ui.timeEdit.dateTime().time().second())
            tomato.append(tomato[len(tomato)-1] + (self.ui.timeEdit_2.dateTime().time().minute()*60) + self.ui.timeEdit_2.dateTime().time().second())
            tomato.append(tomato[len(tomato)-1] + (self.ui.timeEdit.dateTime().time().minute()*60) + self.ui.timeEdit.dateTime().time().second())
            tomato.append(tomato[len(tomato)-1] + (self.ui.timeEdit_2.dateTime().time().minute()*60) + self.ui.timeEdit_2.dateTime().time().second())
            tomato.append(tomato[len(tomato)-1] + (self.ui.timeEdit.dateTime().time().minute()*60) + self.ui.timeEdit.dateTime().time().second())
            tomato.append(tomato[len(tomato)-1] + (self.ui.timeEdit_2.dateTime().time().minute()*60) + self.ui.timeEdit_2.dateTime().time().second())
            tomato.append(tomato[len(tomato)-1] + (self.ui.timeEdit.dateTime().time().minute()*60) + self.ui.timeEdit.dateTime().time().second())
            tomato.append(tomato[len(tomato)-1] + (self.ui.timeEdit_3.dateTime().time().minute()*60) + self.ui.timeEdit_3.dateTime().time().second())
    def stopTomato(self):
        global tomato
        tomato = []
        self.ui.label_22.setText("")
        self.ui.label_28.setText("")
        self.ui.label_30.setText("暂无番茄")
        self.ui.label_31.setText("暂无番茄")
    def immerse(self):
        global isImmerse
        if isImmerse:
            isImmerse = False
            volume.SetMute(0, None)  # 取消静音
            # self.showNormal()
        else:
            isImmerse = True
            volume.SetMute(1, None)  # 静音
            # self.showFullScreen()
    def last(self):
        global musicPoint, bePlayed
        musicPoint -= 1
        if musicPoint == -1:
            musicPoint = len(musicList) - 1
        bePlayed = musicList[musicPoint]
        # 加载音乐文件（支持 MP3/WAV/OGG 等格式）
        pygame.mixer.music.load("C:\\ProgramData\\LearningTools\\music\\" + bePlayed)
        pygame.mixer.music.play()
        self.ui.pushButton_17.setIcon(QIcon(QPixmap.fromImage(ImageQt.toqimage(Image.open('C:\\ProgramData\\LearningTools\\material\\img\\play.png')))))
        # print(musicPoint)
    def next(self):
        global musicPoint, bePlayed
        musicPoint += 1
        if musicPoint == len(musicList):
            musicPoint = 0
        bePlayed = musicList[musicPoint]
        # 加载音乐文件（支持 MP3/WAV/OGG 等格式）
        pygame.mixer.music.load("C:\\ProgramData\\LearningTools\\music\\" + bePlayed)
        pygame.mixer.music.play()
        self.ui.pushButton_17.setIcon(QIcon(QPixmap.fromImage(ImageQt.toqimage(Image.open('C:\\ProgramData\\LearningTools\\material\\img\\play.png')))))
    def sx(self):
        global sxPoint
        sxPoint+=1
        sxPoint = sxPoint%4
        self.ui.pushButton_20.setIcon(QIcon(QPixmap.fromImage(ImageQt.toqimage(Image.open('C:\\ProgramData\\LearningTools\\material\\img\\sx' + str(sxPoint+1) + '.png')))))
    def stop(self):
        global isStop
        if isStop:
            # 开始播放（异步播放）
            pygame.mixer.music.load("C:\\ProgramData\\LearningTools\\music\\" + bePlayed)   
            pygame.mixer.music.play()
            self.ui.pushButton_17.setIcon(QIcon(QPixmap.fromImage(ImageQt.toqimage(Image.open('C:\\ProgramData\\LearningTools\\material\\img\\play.png')))))
            isStop = False
        else:
            pygame.mixer.music.stop()
            self.ui.pushButton_17.setIcon(QIcon(QPixmap.fromImage(ImageQt.toqimage(Image.open('C:\\ProgramData\\LearningTools\\material\\img\\stop.png')))))
            isStop = True
    def voice(self):
        global voiceStep, voiceSize
        voiceSize += voiceStep
        if voiceSize == 0:
            voiceStep = 1
        elif voiceSize == 3:
            voiceStep = -1
        pygame.mixer.music.set_volume((0.33*voiceSize)+0.01)
        self.ui.pushButton_18.setIcon(QIcon(QPixmap.fromImage(ImageQt.toqimage(Image.open('C:\\ProgramData\\LearningTools\\material\\img\\v' + str(voiceSize) + '.png')))))

    def home(self): # 模板跳转
        global tabList
        # print(tabList[0][1])
        if tabList[0][1]:
            for i in range(10):
                if tabList[0][0] == self.ui.tabWidget.widget(i):
                    self.ui.tabWidget.setCurrentIndex(i)
                    break
        else:
            self.ui.tabWidget.removeTab(self.ui.tabWidget.count()-1)
            self.ui.tabWidget.addTab(tabList[0][0], "欢迎")
            self.ui.tabWidget.addTab(tabList[7][0], "✕")
            self.ui.tabWidget.setCurrentIndex(self.ui.tabWidget.count()-2)
            tabList[0][1] = True
    def study(self):
        global tabList
        # print(tabList[0][1])
        if tabList[1][1]:
            for i in range(10):
                if tabList[1][0] == self.ui.tabWidget.widget(i):
                    self.ui.tabWidget.setCurrentIndex(i)
                    break
        else:
            self.ui.tabWidget.removeTab(self.ui.tabWidget.count()-1)
            self.ui.tabWidget.addTab(tabList[1][0], "虚拟自习室")
            self.ui.tabWidget.addTab(tabList[7][0], "✕")
            self.ui.tabWidget.setCurrentIndex(self.ui.tabWidget.count()-2)
            tabList[1][1] = True
    def tomato(self):
        global tabList
        # print(tabList[0][1])
        if tabList[2][1]:
            for i in range(10):
                if tabList[2][0] == self.ui.tabWidget.widget(i):
                    self.ui.tabWidget.setCurrentIndex(i)
                    break
        else:
            self.ui.tabWidget.removeTab(self.ui.tabWidget.count()-1)
            self.ui.tabWidget.addTab(tabList[2][0], "番茄钟")
            self.ui.tabWidget.addTab(tabList[7][0], "✕")
            self.ui.tabWidget.setCurrentIndex(self.ui.tabWidget.count()-2)
            tabList[2][1] = True
    def note(self):
        global tabList
        # print(tabList[0][1])
        if tabList[3][1]:
            for i in range(10):
                if tabList[3][0] == self.ui.tabWidget.widget(i):
                    self.ui.tabWidget.setCurrentIndex(i)
                    break
        else:
            self.ui.tabWidget.removeTab(self.ui.tabWidget.count()-1)
            self.ui.tabWidget.addTab(tabList[3][0], "笔记便签")
            self.ui.tabWidget.addTab(tabList[7][0], "✕")
            self.ui.tabWidget.setCurrentIndex(self.ui.tabWidget.count()-2)
            tabList[3][1] = True
    def date(self):
        global tabList
        # print(tabList[0][1])
        if tabList[4][1]:
            for i in range(10):
                if tabList[4][0] == self.ui.tabWidget.widget(i):
                    self.ui.tabWidget.setCurrentIndex(i)
                    break
        else:
            self.ui.tabWidget.removeTab(self.ui.tabWidget.count()-1)
            self.ui.tabWidget.addTab(tabList[4][0], "学习日历")
            self.ui.tabWidget.addTab(tabList[7][0], "✕")
            self.ui.tabWidget.setCurrentIndex(self.ui.tabWidget.count()-2)
            tabList[4][1] = True
    def census(self):
        global tabList
        # print(tabList[0][1])
        if tabList[5][1]:
            for i in range(10):
                if tabList[5][0] == self.ui.tabWidget.widget(i):
                    self.ui.tabWidget.setCurrentIndex(i)
                    break
        else:
            self.ui.tabWidget.removeTab(self.ui.tabWidget.count()-1)
            self.ui.tabWidget.addTab(tabList[5][0], "学习统计")
            self.ui.tabWidget.addTab(tabList[7][0], "✕")
            self.ui.tabWidget.setCurrentIndex(self.ui.tabWidget.count()-2)
            tabList[5][1] = True
    def about(self):
        global tabList
        # print(tabList[0][1])
        if tabList[6][1]:
            for i in range(10):
                if tabList[6][0] == self.ui.tabWidget.widget(i):
                    self.ui.tabWidget.setCurrentIndex(i)
                    break
        else:
            self.ui.tabWidget.removeTab(self.ui.tabWidget.count()-1)
            self.ui.tabWidget.addTab(tabList[6][0], "关于我们")
            self.ui.tabWidget.addTab(tabList[7][0], "✕")
            self.ui.tabWidget.setCurrentIndex(self.ui.tabWidget.count()-2)
            tabList[6][1] = True
    def useExplain(self):
        webbrowser.open("https://space.bilibili.com/550090338")
    def programDoc(self):
        webbrowser.open("https://space.bilibili.com/550090338")

    def dk(self):
        global dktg
        # 在这里需要专门对于打卡日期进行记录
        # 我需要将每次打卡的日期都存下来,首先判断第一项的日期是否为今天的,如果不是,那就代表需要记录新的日期,需要用for把每项的内容都往后移动
        # 如果是,那就是重复打卡,不认可,什么都不要干
        # 总结时需要进行的计算在timeUpdate里玩,dk函数里不要管
        # 别忘了在打卡结束了把dktg重新提交回数据库
        # 测试
        if dktg[0] != timeStrGet():
            # 时间没重,可以开始记录打卡日期了,另外不需要早退出,因为后续代码逻辑复杂度不高,占不了太多东西
            # 首先需要把原先的所有日期后移,并且还要提前把最后一个日期删了,算了,直接覆写也行
            for i in range(30):
                dktg[i+1] = dktg[i]
            # 移位的本质是克隆与覆写,现在再把落下的第一个给赋值为今天新的日期
            dktg[0] = timeStrGet()
            # 提交数据库
            saveData("dktg", dktg)

        # 以下代码恢复对于打卡图片的显示为主题
        if findData("DK_DATE"):
            if readData("DK_DATE") == datetime.datetime.now().strftime("%Y-%m-%d"):
                img = readData("_DK")
                pixmap = QPixmap.fromImage(ImageQt.toqimage(img))
                self.ui.pushButton_14.setIcon(QIcon(pixmap))
            else:
                img = dkPhoto.makeDke()
                pixmap = QPixmap.fromImage(ImageQt.toqimage(img))
                self.ui.pushButton_14.setIcon(QIcon(pixmap))
                saveData("_DK", img)
                saveData("DK_DATE", datetime.datetime.now().strftime("%Y-%m-%d"))
        else:
            # 走这条线就代表有第一次打卡的可能性，需要创立一个列表数据以实现所有打卡日期的记录
            if findData("dkList"):
                dklist = readData("dkList")
                dklist.append(datetime.datetime.now().strftime("%Y-%m-%d"))
                saveData('dkList', dklist)
            else:
                dklist = [datetime.datetime.now().strftime("%Y-%m-%d")]
                saveData('dkList', dklist)
            img = dkPhoto.makeDke()
            pixmap = QPixmap.fromImage(ImageQt.toqimage(img))
            self.ui.pushButton_14.setIcon(QIcon(pixmap))
            saveData("_DK", img)
            saveData("DK_DATE", datetime.datetime.now().strftime("%Y-%m-%d"))

    def timeUpdate(self):
        global point, tabList, bePlayed, musicPoint, current_time, sche, dktg, lastMusicPoint
        # print(tabList[0][1])
        if self.ui.tabWidget.currentWidget() == None:
            self.ui.tabWidget.addTab(tabList[0][0], "欢迎")
            self.ui.tabWidget.addTab(tabList[7][0], "✕")
            tabList[0][1] = True
            tabList[7][1] = True
        elif self.ui.tabWidget.currentWidget().objectName()=="tab_5":
            for i in range(10):
                if tabList[i][0] == self.ui.tabWidget.widget(point):
                    tabList[i][1] = False
                    break
            self.ui.tabWidget.removeTab(point)
            self.ui.tabWidget.setCurrentIndex(max(point-1, 0))
        else:
            point = self.ui.tabWidget.currentIndex()
        
        # 更新时间
        self.ui.label_6.setText(datetime.datetime.now().strftime("%H:%M:%S"))

        # 更新音乐
        # 获取已播放时间（单位：毫秒）
        current_time = pygame.mixer.music.get_pos()/1000  # 返回整数，如 3050 表示3.05秒

        # 计算总时长（需要手动解析）
        audio = mp3.MP3("C:\\ProgramData\\LearningTools\\music\\" + bePlayed)
        total_duration = audio.info.length  # 单位：秒
        self.ui.horizontalSlider.setValue(current_time/total_duration*100)
        if int(current_time) == int(total_duration):
            if sxPoint == 1:
                musicPoint = random.randint(0,len(musicList))
            elif sxPoint == 3:
                pass
            else:
                musicPoint += 1
            if musicPoint == len(musicList):
                if sxPoint == 0:
                    pass
                elif sxPoint == 2:
                    musicPoint = 0
            bePlayed = musicList[musicPoint]
            # 这里是让单曲循环时音乐还可以继续播
            if sxPoint == 3:
                pygame.mixer.music.load("C:\\ProgramData\\LearningTools\\music\\" + bePlayed)   
                pygame.mixer.music.play()
            elif sxPoint == 0:
                lastMusicPoint = musicPoint
                self.stop()

        if musicPoint != lastMusicPoint:
            willNotPlay = (lastMusicPoint == -1)
            lastMusicPoint = musicPoint
            self.ui.label_5.setText(bePlayed)
            try:
                audio = File("C:\\ProgramData\\LearningTools\\music\\" + musicList[musicPoint])
                if "APIC:" in audio.tags:
                    with open("C:\\ProgramData\\LearningTools\\material\\temporary\\temporary.jpg", "wb") as f:
                        f.write(audio.tags["APIC:"].data)
                    self.ui.pushButton_15.setIcon(QIcon(QPixmap.fromImage(ImageQt.toqimage(Image.open('C:\\ProgramData\\LearningTools\\material\\temporary\\temporary.jpg')))))
                else:
                    self.ui.pushButton_15.setIcon(QIcon(QPixmap.fromImage(ImageQt.toqimage(Image.open('C:\\ProgramData\\LearningTools\\material\\img\\music.png')))))
            except:
                self.ui.pushButton_15.setIcon(QIcon(QPixmap.fromImage(ImageQt.toqimage(Image.open('C:\\ProgramData\\LearningTools\\material\\img\\music.png')))))

            # 不要忘记切歌!
            if not willNotPlay:
                pygame.mixer.music.load("C:\\ProgramData\\LearningTools\\music\\" + bePlayed)   
                pygame.mixer.music.play()

        if len(tomato) != 0:
            for i in range(12):
                if tomato[i] <= int(time.time()) <= tomato[i+1]:
                    t = tomato[i+1] - int(time.time())
                    self.ui.label_28.setText("时间：" + ("0"+str(t//60))[-2:] + ":" + ("0"+str(t%60))[-2:])
                    self.ui.label_31.setText(("0"+str(t//60))[-2:] + ":" + ("0"+str(t%60))[-2:])
                    if (i%8) in [0,2,4,6]:
                        self.ui.label_22.setText("番茄状态：工作")
                        self.ui.label_30.setText("工作")
                    elif (i%8) in [1,3,5]:
                        self.ui.label_22.setText("番茄状态：休息")
                        self.ui.label_30.setText("休息")
                    elif (i%8) == 7:
                        self.ui.label_22.setText("番茄状态：长休息")
                        self.ui.label_30.setText("长休息")
        saveData("jjs", self.ui.textEdit.toPlainText())
        if not datetime.datetime.now().strftime("%Y-%m-%d") in sche:
            sche[datetime.datetime.now().strftime("%Y-%m-%d")] = [["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""],["",""]]
        for i in range(25):
                self.ui.tableWidget.item(i,0).setText(sche[datetime.datetime.now().strftime("%Y-%m-%d")][i][0])
                self.ui.tableWidget.item(i,1).setText(sche[datetime.datetime.now().strftime("%Y-%m-%d")][i][1])
        sche[dateStr] = [
            [self.ui.tableWidget_2.item(0,0).text(),self.ui.tableWidget_2.item(0,1).text()],
            [self.ui.tableWidget_2.item(1,0).text(),self.ui.tableWidget_2.item(1,1).text()],
            [self.ui.tableWidget_2.item(2,0).text(),self.ui.tableWidget_2.item(2,1).text()],
            [self.ui.tableWidget_2.item(3,0).text(),self.ui.tableWidget_2.item(3,1).text()],
            [self.ui.tableWidget_2.item(4,0).text(),self.ui.tableWidget_2.item(4,1).text()],
            [self.ui.tableWidget_2.item(5,0).text(),self.ui.tableWidget_2.item(5,1).text()],
            [self.ui.tableWidget_2.item(6,0).text(),self.ui.tableWidget_2.item(6,1).text()],
            [self.ui.tableWidget_2.item(7,0).text(),self.ui.tableWidget_2.item(7,1).text()],
            [self.ui.tableWidget_2.item(8,0).text(),self.ui.tableWidget_2.item(8,1).text()],
            [self.ui.tableWidget_2.item(9,0).text(),self.ui.tableWidget_2.item(9,1).text()],
            [self.ui.tableWidget_2.item(10,0).text(),self.ui.tableWidget_2.item(10,1).text()],
            [self.ui.tableWidget_2.item(11,0).text(),self.ui.tableWidget_2.item(11,1).text()],
            [self.ui.tableWidget_2.item(12,0).text(),self.ui.tableWidget_2.item(12,1).text()],
            [self.ui.tableWidget_2.item(13,0).text(),self.ui.tableWidget_2.item(13,1).text()],
            [self.ui.tableWidget_2.item(14,0).text(),self.ui.tableWidget_2.item(14,1).text()],
            [self.ui.tableWidget_2.item(15,0).text(),self.ui.tableWidget_2.item(15,1).text()],
            [self.ui.tableWidget_2.item(16,0).text(),self.ui.tableWidget_2.item(16,1).text()],
            [self.ui.tableWidget_2.item(17,0).text(),self.ui.tableWidget_2.item(17,1).text()],
            [self.ui.tableWidget_2.item(18,0).text(),self.ui.tableWidget_2.item(18,1).text()],
            [self.ui.tableWidget_2.item(19,0).text(),self.ui.tableWidget_2.item(19,1).text()],
            [self.ui.tableWidget_2.item(20,0).text(),self.ui.tableWidget_2.item(20,1).text()],
            [self.ui.tableWidget_2.item(21,0).text(),self.ui.tableWidget_2.item(21,1).text()],
            [self.ui.tableWidget_2.item(22,0).text(),self.ui.tableWidget_2.item(22,1).text()],
            [self.ui.tableWidget_2.item(23,0).text(),self.ui.tableWidget_2.item(23,1).text()],
            [self.ui.tableWidget_2.item(24,0).text(),self.ui.tableWidget_2.item(24,1).text()]
            ]
        # print(sche[dateStr])
        saveData("sche", sche)

        # 这里是数据计算与总结,用来评估学习情况使用的
        allDays = 0
        continualDays = 0
        temporaryList = []
        for i in dktg:
            # 先查下一个月总共学习多少天
            if i[0:6] == timeStrGet()[0:6]:
                allDays += 1
                temporaryList.append(int(i[6:8]))
                # 这里存数据是为了方便计算连续天数
        if len(temporaryList) != 0:
            # 布什没打卡记录就不要计算了好吗?
            temporaryPoint = temporaryList[0]
        for i in temporaryList:
            if i == temporaryPoint:
                continualDays += 1
            temporaryPoint -= 1
        # 结束计算
        if 0 <= allDays <= 5:
            allDays = str(allDays)
            text = "本月记录到" + allDays + "天学习记录，知识积累需要稳定的输入频率哦~建议从每天15分钟微习惯开始，逐步建立学习节奏！"
        elif 6 <= allDays <= 12:
            allDays = str(allDays)
            text = "本月有" + allDays + "天投入学习，已形成初步的学习意识！如果能将学习日分布得更均匀些，效果会更好呢~"
        elif 13 <= allDays <= 19:
            allDays = str(allDays)
            text = allDays + "天的学习记录很棒！超过半数天数保持学习状态，这种持续性值得点赞！继续保持这个势头吧！"
        elif 20 <= allDays <= 26:
            allDays = str(allDays)
            text = allDays + "天高频学习太优秀了！您已形成稳定的学习周期，知识巩固效果会随着时间指数级增长~"
        elif 27 <= allDays <= 30:
            allDays = str(allDays)
            text = "接近全勤的" + allDays + "天！这种高度自律令人钦佩，您正在用坚持书写属于自己的成长曲线！"
        text = text + "\n\n"
        if 1 <= continualDays <= 3:
            continualDays = str(continualDays)
            text = text + "当前最长连续学习" + continualDays + "天，建议尝试突破3日周期，连续学习带来的知识串联效果会超乎想象！"
        elif 4 <= continualDays <= 6:
            continualDays = str(continualDays)
            text = text + continualDays + "天的持续学习已初见成效！如果能将学习模块化（如设立周目标），连续性会带来更大收益~"
        elif 7 <= continualDays <= 14:
            continualDays = str(continualDays)
            text = text + continualDays + "天的知识马拉松太棒了！这种持续输入正在重塑您的大脑神经连接，坚持就是质变的前奏！"
        elif 15 <= continualDays <= 21:
            continualDays = str(continualDays)
            text = text + "连续" + continualDays + "天的学习习惯已接近养成！科学研究表明21天是习惯固化期，您马上就要突破这个里程碑了！"
        elif 22 <= continualDays <= 30:
            continualDays = str(continualDays)
            text = text + "惊人的" + continualDays + "天持续学习！您已进入'心流-惯性'的正向循环，这是顶级学习者的标志性特征！"
        self.ui.textEdit_2.setText(text)
        allDays = str(allDays)
        continualDays = str(continualDays)
        self.ui.label_16.setText("在这个月内，您已连续学习 " + continualDays + " 天")
        self.ui.label_19.setText("总计学习了 " + allDays + " 天")
        

if __name__ == '__main__':
    app = QApplication([])  # 启动一个应用
    window = MainWindow()  # 实例化主窗口
    window.show()  # 展示主窗口
    app.exec()  # 避免程序执行到这一行后直接退出